package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IFollowService followService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSave = save(blog);
        if (!isSave) {
            return Result.fail("发布笔记失败");
        }
        //获取有关粉丝
        //获取多个数据项时，要指定.list()，要不然返回的是queryWrapper对象
        List<Follow> followList = followService.query().eq("follow_user_id", user.getId()).list();
        //发送笔记id到粉丝的笔记set中
        for (Follow follow : followList) {
            stringRedisTemplate.opsForZSet().add(FEED_KEY+follow.getUserId().toString(),blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long lastId, int offset) {
        //sortedset请求的4个参数：max min count offset
        UserDTO user = UserHolder.getUser();
        //去查当前用户的邮箱——默认是升序，因为要获取最新的，所以要reverse
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(FEED_KEY + user.getId().toString(), 0, lastId, offset, 2);
        if (typedTuples==null|| typedTuples.isEmpty()) {
            return Result.ok();
        }
        long minTime =  0l;
        int os=1;
        List<Blog> blogList = new ArrayList<>();
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            Long id = Long.valueOf(typedTuple.getValue());
            //由id去查blog
            Blog blog = query().eq("id", id).one();
            //查询blog有关的用户信息
            queryBlogUserInfo(blog);
            //查询blog是否被当前用户点赞
            isBlogLiked(blog);
            blogList.add(blog);
            //获取当前blog的时间戳
            Long score = typedTuple.getScore().longValue();
            if (!Objects.equals(score, minTime)){
                minTime=score;
                os=1;
            }else {
                os+=1;
            }
        }
        //返回笔记集合list，minTime，offset
        ScrollResult scrollResult = ScrollResult.builder()
                .list(blogList)
                .miniTime(minTime)
                .offset(os)
                .build();
        return Result.ok(scrollResult);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //由userId查询用户信息
        queryBlogUserInfo(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryCurrentHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            this.queryBlogUserInfo(blog);
            this.isBlogLiked(blog);
        });
        return Result.ok(records);

    }

    @Override
    public void likeBlog(Long id) {
        //判断是否点过赞
        UserDTO user = UserHolder.getUser();
        Double isMember = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, user.getId().toString());
        //是，点赞数减一，并删除redis记录
        if (isMember!=null){
            boolean update = update().setSql("liked = liked - 1").eq("id", id).update();
            if (BooleanUtil.isTrue(update)){
                stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY+id,user.getId().toString());
            }
        }else {
            //否，点赞数+1
            // 修改点赞数量
            boolean update = update().setSql("liked = liked + 1").eq("id", id).update();
            if (BooleanUtil.isTrue(update)){
                //修改数据库成功，同步到redis中
                //基于时间戳来赋值
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY+id, String.valueOf(user.getId()),System.currentTimeMillis());
            }
        }
    }

    @Override
    public Result likeBlogRank(Long id) {

        //从redis中获取前5名
        Set<String> userIdSet = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        if (userIdSet==null||userIdSet.isEmpty()){
            return Result.ok();
        }
        //基于userId查询UserDTO
        List<Long> userIds = userIdSet.stream().map(Long::valueOf).collect(Collectors.toList());
        //join拼接list
        String strFormat = StrUtil.join(",", userIds);
//        List<UserDTO> userDTOS = userService.listByIds(userIds).stream().map(user -> (BeanUtil.copyProperties(user, UserDTO.class)))
//                .collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.query().in("id", userIds).last("ORDER BY FIELD(id," + strFormat + ")")
                .list()
                .stream().map(user -> (BeanUtil.copyProperties(user, UserDTO.class))).collect(Collectors.toList());
        return Result.ok(userDTOS);
    }



    private void isBlogLiked(Blog blog) {
        //设置isLike字段
        UserDTO user = UserHolder.getUser();
        if (user==null){
            return;
        }
        Double isMember = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blog.getId().toString(), user.getId().toString());
        blog.setIsLike(BooleanUtil.isTrue(isMember!=null));
    }
    private void queryBlogUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
